# Copyright 2023 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""market_place_to_hub

Revision ID: 4acd9430b093
Revises: 959ae00528ad
Create Date: 2023-04-26 22:41:59.726305

"""
import sqlalchemy as sa
from alembic import op

from mlrun.api.utils.db.sql_collation import SQLCollationUtil

# revision identifiers, used by Alembic.
revision = "4acd9430b093"
down_revision = "959ae00528ad"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    rename_hub_marketplace_table("marketplace_sources", "hub_sources")
    # ### end Alembic commands ###


def downgrade():
    pass
    # ### commands auto generated by Alembic - please adjust! ###
    rename_hub_marketplace_table("hub_sources", "marketplace_sources")
    # ### end Alembic commands ###


def rename_hub_marketplace_table(current_name, new_name):
    op.create_table(
        new_name,
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column(
            "name",
            sa.String(255, collation=SQLCollationUtil.collation()),
            nullable=True,
        ),
        sa.Column("index", sa.Integer(), nullable=True),
        sa.Column("created", sa.TIMESTAMP(), nullable=True),
        sa.Column("updated", sa.TIMESTAMP(), nullable=True),
        sa.Column("object", sa.JSON(), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("name", name=f"_{new_name}_uc"),
    )
    hub_sources = sa.sql.table(
        new_name,
        sa.Column("name", sa.String(255), nullable=True),
        sa.Column("object", sa.JSON, nullable=True),
        sa.Column("index", sa.Integer, nullable=True),
        sa.Column("created", sa.TIMESTAMP, nullable=True),
        sa.Column("updated", sa.TIMESTAMP, nullable=True),
    )
    connection = op.get_bind()
    select_previous_table_data_query = connection.execute(
        f"SELECT * FROM {current_name}"
    )
    previous_table_data = select_previous_table_data_query.fetchall()
    op.bulk_insert(hub_sources, previous_table_data)
    op.drop_table(current_name)
